package com.baiyue.utils;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wubo
 */
public class ThreadPoolUtil {
    /**
     * 核心线程数
      */
    private static final int SIZE_CORE_POOL = 5;
    /**
     * 线程池维护线程的最大数量
     */
    private static final int SIZE_MAX_POOL = 9;
    /**
     * 线程池维护线程所允许的空闲时间
     */
    private static final long TIME_KEEP_ALIVE = 2000;
    /**
     * 任务队列为无界队列
     */
    private static final LinkedBlockingQueue<Runnable> QUEUE_TASK = new LinkedBlockingQueue<>();

    private static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(SIZE_CORE_POOL, SIZE_MAX_POOL, TIME_KEEP_ALIVE,
            TimeUnit.MILLISECONDS,QUEUE_TASK, new ThreadPoolExecutor.CallerRunsPolicy());

    static {
        POOL.prestartAllCoreThreads();
        // 添加RejectedExecutionHandler来处理异常情况
        POOL.setRejectedExecutionHandler((r, executor) -> {
            if (executor.isShutdown()) {
                return;
            }
            try {
                // 将任务重新放回到队列中
                executor.getQueue().put(r);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
    }

    /**
     * 获取线程池实例
     */
    public static ThreadPoolExecutor getPool() {
        return POOL;
    }

    /**
     * 获取当前线程数
     */
    public static int getCurrentPoolSize() {
        return POOL.getPoolSize();
    }

    /**
     * 获取任务队列大小
     */
    public static int getQueueSize() {
        return POOL.getQueue().size();
    }

    /**
     * 线程监控
     */
    public static void printCurrentThread() {
        Thread t = Thread.currentThread();
        System.out.println("当前线程池正在" + t.getName() + "线程中执行任务");
    }
}
